//
//  TFPhotoPickerAlbumView.m
//  PhotoDemoProject
//
//  Created by TFAppleWork-Summer on 2016/12/6.
//  Copyright © 2016年 TFAppleWork-Summer. All rights reserved.
//

#import "TFPhotoPickerAlbumView.h"
#import "TFPhotoPickerAlbumTableViewCell.h"
#import "TFPhotoPickerHelper.h"
#import "UIColor+TFPhoto.h"
#import "TFPhotoHandler.h"

@interface TFPhotoPickerAlbumView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong, readwrite) NSArray<TFPhotoPickerAlbumModel *> *albumListArray;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, weak) id<TFPhotoPickerAlbumViewDelegate> delegate;

@property (nonatomic, strong, readwrite) NSMutableArray<TFPhotoPickerItemModel *> *shareTypeItemModelArray;


@end

@implementation TFPhotoPickerAlbumView

+ (instancetype)showInView:(UIView *)view withMomentAlbumModel:(TFPhotoPickerAlbumModel *)momentAlbumModel selectedAlbumModel:(TFPhotoPickerAlbumModel *)selectedAlbumModel mediaTypes:(NSArray *)mediaTypes delegate:(id<TFPhotoPickerAlbumViewDelegate>)delegate {
    TFPhotoPickerAlbumView *albumView = [[TFPhotoPickerAlbumView alloc] init];
    //获取数据模型
    albumView.shareTypeItemModelArray = [NSMutableArray array];
    albumView.delegate = delegate;
    NSMutableArray *cacheArray = [NSMutableArray array];
    albumView.albumListArray = [TFPhotoPickerHelper getAlbumListArrayWithMediaTypes:mediaTypes insertMomentAlbumModel:momentAlbumModel selectedAlbumModel:selectedAlbumModel enumerateItemModels:^(TFPhotoPickerItemModel *itemModel) {
            [albumView.shareTypeItemModelArray addObject:itemModel];
            [cacheArray insertObject:itemModel.asset atIndex:0];
    }];
    [view addSubview:albumView];
    albumView.translatesAutoresizingMaskIntoConstraints = NO;
    albumView.tableView.translatesAutoresizingMaskIntoConstraints = NO;

    NSDictionary *viewDic = @{@"albumView":albumView,@"tableView":albumView.tableView};
    
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[albumView]|" options:0 metrics:nil views:viewDic]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[albumView]|" options:0 metrics:nil views:viewDic]];
    
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[tableView]|" options:0 metrics:nil views:viewDic]];
    if (CGRectGetMinY(view.frame)==64.0) {
        [NSLayoutConstraint constraintWithItem:albumView.tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:albumView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0].active = YES;
    }
    else {
        [NSLayoutConstraint constraintWithItem:albumView.tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:albumView attribute:NSLayoutAttributeTop multiplier:1.0 constant:64.0].active = YES;
    }
    
    //更新UI
    CGFloat cellHeight = albumView.tableView.rowHeight;
    CGFloat tableViewHeight = MIN(cellHeight*4, albumView.albumListArray.count*cellHeight);
    albumView.tableView.frame = CGRectMake(0, 0, 0, tableViewHeight);
    //添加高度约束
    [NSLayoutConstraint constraintWithItem:albumView.tableView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:tableViewHeight].active = YES;
    //刷新数据
    [albumView.tableView reloadData];
    //出现动画
    [albumView showAlbumListTableViewWithHidden:NO];
    return albumView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.tableView];
        self.backgroundColor = [UIColor tfPhoto_hexColorWith:@"#000000" alpha:0.4];
        self.alpha = 0.0;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(p_viewDidTapAction)]];
    }
    return self;
}

- (void)p_viewDidTapAction {
    [self showAlbumListTableViewWithHidden:YES];
}

- (void)showAlbumListTableViewWithHidden:(BOOL)hidden {
    [UIView animateWithDuration:0.8 delay:0.0 usingSpringWithDamping:0.6f initialSpringVelocity:0.55f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        if (hidden) {
            self.alpha = 0.0;
            self.tableView.transform = CGAffineTransformIdentity;
            if ([self.delegate respondsToSelector:@selector(photoPickerAlbumViewWillDissmiss:)]) {
                [self.delegate photoPickerAlbumViewWillDissmiss:self];
            }
        }
        else {
            self.tableView.transform = CGAffineTransformMakeTranslation(0.0, CGRectGetHeight(self.tableView.frame));
            self.alpha = 1.0;
        }
    } completion:^(BOOL finished) {
        if (hidden) {
            [self removeFromSuperview];
        }
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.albumListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TFPhotoPickerAlbumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTFPhotoPickerAlbumTableViewCellIdentifier];
    cell.model = self.albumListArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(photoPickerAlbumView:didSelectRowAtIndexPath:)]) {
        [self.delegate photoPickerAlbumView:self didSelectRowAtIndexPath:indexPath];
    }
    [self showAlbumListTableViewWithHidden:YES];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (CGRectContainsPoint(self.tableView.frame, point)) {
        [self.gestureRecognizers lastObject].enabled = NO;
        return self.tableView;
    }
    else {
        [self.gestureRecognizers lastObject].enabled = YES;
        return self;
    }
    
}

#pragma mark - lazy load.

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), 0.0) style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = kTFPhotoPickerAlbumThumnailImageSize+20.0;
        [_tableView registerClass:[TFPhotoPickerAlbumTableViewCell class] forCellReuseIdentifier:kTFPhotoPickerAlbumTableViewCellIdentifier];
    }
    return _tableView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
